//
//  Button.m
//  FunnyRacing
//
//  Created by vy phan on 16/03/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "Button.h"
#import "Game.h"
#import "GraphicConstant.h"

@implementation Button

@synthesize type;

-(id)initWithType:(int)type_
{
	//Button* button = nil;
	spriteSheet = [CCSpriteSheet spriteSheetWithFile:@"arrows.png" capacity:1];
	if (type_ == DPAD_DOWN) {
		self = [[Button alloc]initWithTexture:spriteSheet.texture rect:CGRectMake(0, 0, DPAD_BUTTON_W, DPAD_BUTTON_H)];
		self.type = DPAD_DOWN;
	}
	if (type_ == DPAD_UP) {
		self = [[Button alloc]initWithTexture:spriteSheet.texture rect:CGRectMake(DPAD_BUTTON_W, 0, DPAD_BUTTON_W, DPAD_BUTTON_H)];
		self.type = DPAD_UP;
	}
	if (type_ == DPAD_LEFT) {
		self = [[Button alloc]initWithTexture:spriteSheet.texture rect:CGRectMake(2 * DPAD_BUTTON_W, 0, DPAD_BUTTON_W, DPAD_BUTTON_H)];
		self.type = DPAD_LEFT;
	}
	if (type_ == DPAD_RIGHT) {
		self = [[Button alloc]initWithTexture:spriteSheet.texture rect:CGRectMake(3 * DPAD_BUTTON_W, 0, DPAD_BUTTON_W, DPAD_BUTTON_H)];
		self.type = DPAD_RIGHT;
	}
	
	self.position = CGPointZero;
	return self;
}

- (void)draw {
	glEnableClientState(GL_VERTEX_ARRAY);
	
	static GLfloat squareVertices[8];
	squareVertices[0] = squareVertices[6] = 0;//position_.x - anchorPoint_.x*rect_.size.width + rect_.origin.x;
	squareVertices[1] = squareVertices[3] = 0;//position_.y - anchorPoint_.y*rect_.size.height +rect_.origin.y;
	squareVertices[2] = squareVertices[4] = squareVertices[0] + rect_.size.width;
	squareVertices[5] = squareVertices[7] = squareVertices[1] + rect_.size.height;
	
	glColor4ub(255, 0, 0, 255);
	
	glVertexPointer(2, GL_FLOAT, 0, squareVertices);
	glDrawArrays(GL_LINE_LOOP, 0, 4);
	
	glColor4ub(255, 255, 255, 255);
	
	glDisableClientState(GL_VERTEX_ARRAY);
}

- (BOOL)isTouchEnabled {
	return isTouchEnabled;
}

- (void)setIsTouchEnabled:(BOOL)enabled {
	if (isTouchEnabled != enabled) {
		isTouchEnabled = enabled;
		
		if (isTouchEnabled)
			[[CCTouchDispatcher sharedDispatcher] addStandardDelegate:self priority:priority];
		else
			[[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
	}
}

- (BOOL)isSelected {
	return isSelected;
}

- (void)onExit {
	
	if (isTouchEnabled)
		[[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
	
	[super onExit];
}

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	UITouch *touch = [touches anyObject];
	CGPoint point = [touch locationInView:[touch view]];
	int posX = self.position.x;
	int posY = self.position.y;
	if (point.x < posX + 20 && point.x > posX - 20
		&&
		point.y < posY + 20 && point.y > posY - 20
		) {
		printf("aaaaaaaaaaaaaa");
	}
}
//- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{}
//- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
//- (void)ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;

@end
